﻿using SerialPortLib;
using System.IO.Ports;
namespace OU.SerialPort.Com
{
    public class ComLib : IComLib
    {
        public static SerialPortInput? serialPort = null;//串口
        #region 打开关闭切换串口
        public string OpenCloseCom(string portName)
        {
            if (serialPort != null)
            {
                if (serialPort.IsConnected)
                {
                    serialPort.Disconnect();
                    serialPort = null;
                    return "连接串口";
                }
                else
                {
                    if (!serialPort.Connect())
                    {
                        serialPort.Disconnect();
                        serialPort = null;
                        return "串口不存在或被占用";
                    }
                }
            }
            else
            {
                serialPort = new SerialPortInput();
                serialPort.ConnectionStatusChanged -= Conection;
                serialPort.MessageReceived -= MessageReceived;
                serialPort.ConnectionStatusChanged += Conection;
                serialPort.MessageReceived += MessageReceived;
                serialPort.SetPort(portName, 115200, StopBits.One,Parity.Even);
                if (!serialPort.Connect())
                {
                    return "串口不存在或被占用";
                }
            }
            return "关闭串口";
        }
        #endregion
        #region 连接事件
        private void Conection(object sender, ConnectionStatusChangedEventArgs args)
        {
            if (args.Connected)
            {

            }
            else
            {

            }

        }
        #endregion
        #region 接受事件带接受方法
        public string datarecived = "";
        public string RrturnCMD = "";
        public event Action<byte[]>? MessageReceive;


        private void MessageReceived(object sender, MessageReceivedEventArgs args)
        {
   
        }



        ///不同指令回馈
        public void CMDID(string CMD, string value)
        {

        }
        #endregion
        #region 发送指令
        public bool SendMessge(byte[] bytes)
        {
            if (serialPort == null) return false;
            if (serialPort.SendMessage(bytes))
            {
                return true;
            }
            else return false;
        }
        public async Task<bool> SendMessgeAsync(byte[] bytes) => await Task.Run(() => { return SendMessge(bytes); });
        #endregion


    }
}
